package com.zlyx.easy.jedis.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.zlyx.easy.core.refresh.IHandlerOnChanged;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;

@Component
public class JedisUtils implements InitializingBean, IHandlerOnChanged {

	private static JedisPool jedisPool;

	@Value("${spring.redis.host}")
	private String host;

	@Value("${spring.redis.password}")
	private String password;

	@Value("${spring.redis.port}")
	private int port;

	@Value("${spring.redis.timeout}")
	private int timeout;

	@Value("${spring.redis.database}")
	private int database;

	@Override
	public void doOnChanged(ApplicationContext context) throws Exception {
		jedisPool.close();
	}

	public static Long publish(String channel, String message) {
		return jedisPool.getResource().publish(channel, message);
	}

	public static void subscribe(JedisPubSub jedisPubSub, String... channels) {
		jedisPool.getResource().subscribe(jedisPubSub, channels);
	}

	public static JedisPool jedisPool() {
		return jedisPool;
	}

	public static Jedis jedis() {
		return jedisPool.getResource();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password, database);
	}
}